package thread.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 一、用于解决多线程安全问题的方式
 */
public class LockTest {
    public static void main(String[] args) {
        new Thread(new Ticket(), "①").start();//卖票产生多线程安全问题
        new Thread(new Ticket(), "②").start();
    }
}

/**
 * 1 同步代码块
 * 2 同步方法
 * 3 lock上锁 finnally取消锁
 */
class Ticket implements Runnable {

    private int ticket = 100;

    private Lock lock = new ReentrantLock();

    @Override
    public  void run() {//synchronized 修饰
        while (true) {

            lock.lock();//上锁

            try {
                Thread.sleep(20);
//                synchronized (this) {

                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "号窗口售票;余票" + --ticket + "张");
                }

//                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
